/*
 * @Description: 很多通用方法都写在这里
 * @Author: youzi
 * @Date: 2019-07-18 11:26:32
 * @LastEditors: youzi
 * @LastEditTime: 2020-07-29 10:15:19
 * @todo:
 */
import FileOperation from "./file-operation";
import { onMediumIdChange, onLargeIdChange } from "./handle-product-id-change";
export { FileOperation, onMediumIdChange, onLargeIdChange };

export function triggerWindowResizeEvent() {
  let event = document.createEvent("HTMLEvents");
  event.initEvent("resize", true, true);
  event.eventType = "message";
  window.dispatchEvent(event);
}

/* export const nestedObjToString = (key, obj) => {
  let result = '';
  Object.keys(obj).forEach(el => {
    result = result.concat(key, '.', el, '=', obj[el], '&');
  });
  return result.slice(0, result.length - 1);
}; */
/**
 * @description: 上下两个方法都是在使用框架自带的AJAX请求时，当出现对象嵌套使用的情况，要调用这个方法，将嵌套对象进行二次改造，才能传到后台，不然只能传[object, Object]
 * @param {string, obj} key是对象的名字，obj是对象，例如：'key', {a: 10, b: 10}
 * @return: obj, 组成对象返回，形如 {key.a: 10, key.b: 20, ...}
 * @logic:
 * @editor: youzi
 * @Date: 2019-09-02 09:29:11
 */
export const nestedObjToString = (key, obj) => {
  let tmpObj = {};
  Object.keys(obj).forEach(el => {
    let tmpKey = key + "." + el;
    tmpObj[tmpKey] = obj[el];
  });
  return tmpObj;
};

/**
 * 用于对上传的数据进行合理性验证，过滤null, undefined, [], {}，特别注意不过滤空串，且没有做SQL注入防护
 * @param {val} any val: 需要验证的值
 * @return : boolean 合理的数据返回true，不合理的返回false
 * @author: youzi
 * @Date: 2019-10-23 16:10:22
 */
export const filterInputData = val => {
  let type = typeof val;
  let notFilter = ["boolean", "string", "number"];
  if (notFilter.includes(type)) {
    return true;
  }
  if (!!val) {
    if (Array.isArray(val)) {
      return val.length !== 0;
    }
    if (type === "object") {
      return Object.keys(val).length !== 0;
    }
    return true;
  } else {
    // else 可能的值有： null, undefined
    return false;
  }
};

/**
 * @desc: 提交前的处理函数
 * @param {object} values 表单提交的数据对象
 * @param {object} formItem 表单渲染对象
 * @return {object}: 过滤后的对象
 * @author: youzi
 */
export const beforeSubmit = (values, formItem) => {
  let tmpObj = {};
  Object.keys(values).forEach((key, idx) => {
    if (filterInputData(values[key])) {
      if (typeof values[key] === "string") {
        tmpObj[key] = values[key].trim();
      } else {
        tmpObj[key] = values[key];
      }
      // 对时间格式特殊化处理
      if (key.includes("Date")) {
        tmpObj[key] = values[key].format("YYYY-MM-DD");
      }
    }
    if (formItem[idx] && formItem[idx].type === "file") {
      let el = formItem[idx];
      if (!!el.fileList.length) {
        let tmpList = [];
        el.fileList.forEach(file => {
          tmpList.push(file.id);
        });
        let tmpStr = tmpList.join(",");
        tmpObj[el.decorator] = tmpStr;
      }
    }
  });
  return tmpObj;
};

/**
 * @desc: 大写下划线转驼峰命名
 * @param {string} s
 * @return: 驼峰命名
 * @author: youzi
 */
// 下划线转换驼峰
export const upperLodashToCamel = s => {
  let name = s.toLowerCase();
  return name.replace(/\_(\w)/g, function(all, letter) {
    return letter.toUpperCase();
  });
};

/**
 * @desc: 截取日期，忽略时间
 * @param {string}
 * @return: 日期
 * @author: youzi
 */
export const dateRender = val => {
  return typeof val === "string" ? val.split(" ")[0] : "";
};

/**
 * @desc: 渲染数字，三个数字间加逗号
 * @param {string} val
 * @return {string}
 * @author: youzi
 */
export const amountRender = val => {
  return typeof val === "number" || typeof val === "string"
    ? val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    : "";
};

/**
 * @desc: 渲染金额，保留小数后两位
 * @param {string} val
 * @return {string}
 * @author: youzi
 */
export const moneyRender = val => {
  return Number.parseFloat(val).toFixed(2);
};

/**
 * @desc: 初始化数字类型
 * @param {string | number} val
 * @return {number}:
 * @author: youzi
 */
export const initNumber = val => {
  return val ? Number.parseFloat(val) : val;
};

/**
 * @desc: 时间校验函数
 * @param {object} moment对象
 * @author: youzi
 */
export const handleDateValidate = (rule, end, callback, start) => {
  if (end.valueOf() < start.valueOf()) {
    callback("结束时间应该大于开始时间");
  } else callback();
};

/**
 * @desc: 给columns添加ellipsis: true
 * @param {object[]} columns 列表数组
 * @return {object[]}
 * @author: youzi
 */
export const addColumnEllipsis = columns => {
  // el: { dataIndex: "projectName", title: "项目名称", align: "center" },
  return columns.map(el => {
    if (el.dataIndex !== "operation") {
      el.ellipsis = true;
    }
    // el.align = "center";
    return el;
  });
};

export const renderYesOrNo = val => {
  return val === 1 ? "是" : "否";
};

/**
 * @desc: 正则表达式
 * @author: youzi
 */
export const regexp = {
  mail: /^\w+([._\\-]*\w)*@(\w+[-\w]*\w+.){1,63}\w+$/,
  phone: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/
};

/**
 * @desc: 供应商下拉框数组中添加黑名单数据，显示非黑名单供应商+该条记录的供应商
 * @param {object} initRecord 该条记录
 * @param {object[]} allSuppliers 非黑名单数组
 * @return {object[]}
 * @author: youzi
 */
export const pushInitRecordSupplier = (initRecord, allSuppliers) => {
  // debugger;
  let hasInitRecordSupplier = false;
  let initRecordSupplier = initRecord.supplierId;
  let name = initRecord.supplierName;
  for (const el of allSuppliers) {
    if (el.id === initRecordSupplier || el.value === initRecordSupplier) {
      hasInitRecordSupplier = true;
      break;
    }
  }
  if (!hasInitRecordSupplier) {
    allSuppliers.unshift({
      id: initRecordSupplier,
      supplierName: name,
      value: initRecordSupplier,
      label: name
    });
  }
  return allSuppliers;
};

/**
 * @desc: search-view表单格式
 * @author: youzi
 */
export const formItemLayout = {
  labelCol: { span: 9 },
  wrapperCol: { span: 15 }
};

/**
 * @desc: 弹窗edit时的表单格式
 * @author: youzi
 */
export const editFormItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 12 }
};

/**
 * @desc: 根据输入值，过滤select组件下拉框选项
 * @param {string} input 输入值
 * @param {object} option 下拉框原生的节点对象
 * @return {boolean}
 * @author: youzi
 */
export const filterOption = (input, option) => {
  // debugger;
  return (
    option.componentOptions.children[0].text
      .toLowerCase()
      .indexOf(input.toLowerCase()) >= 0
  );
};
